package com.tchy.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.tchy.cloud.entity.AColumnsEntity;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.ComboTree;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MutiLangUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.tag.vo.easyui.ComboTreeModel;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 分类标签控制层
 * Created by zjy on 2015/3/21.
 */
@Scope("prototype")
@Controller
@RequestMapping("/columnsController")
public class AColumnsController extends BaseController {


    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(AColumnsController.class);

    @Autowired
    private SystemService systemService;

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    @RequestMapping(params = "columns")
    public ModelAndView depart(HttpServletRequest request) {

        return new ModelAndView("clound/articleManager/columns/columnsList");
    }


    /**
     * 分类标签树形表格数据
     * @param columns
     * @param request
     * @param response
     * @param treegrid
     * @return
     */
    @RequestMapping(params = "columnsgrid")
    @ResponseBody
    public Object columnsgrid(AColumnsEntity columns, HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
        CriteriaQuery cq = new CriteriaQuery(AColumnsEntity.class);
        if("yes".equals(request.getParameter("isSearch"))){
            treegrid.setId(null);
            columns.setColumnsId(null);
        }
        if(null != columns.getTitle()){
            org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, columns);
        }
        if (treegrid.getId() != null) {
            cq.eq("aColumnsEntity.columnsId", Integer.parseInt(treegrid.getId()));
        }
        if (treegrid.getId() == null) {
            cq.isNull("aColumnsEntity");
//            cq.isNull("TBbPGoodsCategoryEntity");
        }
        cq.addOrder("sort", SortDirection.asc);


        cq.eq("deleted",0);

        cq.add();
        List<TreeGrid> columnsList =null;
        columnsList=systemService.getListByCriteriaQuery(cq, false);
        if(columnsList.size()==0&&columns.getTitle()!=null){
            cq = new CriteriaQuery(AColumnsEntity.class);
            AColumnsEntity parCategoryt = new AColumnsEntity();
            columns.setaColumnsEntity(parCategoryt);
            org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, columns);
            columnsList =systemService.getListByCriteriaQuery(cq, false);
        }
        List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
        TreeGridModel treeGridModel = new TreeGridModel();
        treeGridModel.setTextField("title");
        treeGridModel.setParentText("aColumnsEntity_title");
        treeGridModel.setParentId("aColumnsEntity_columnsId");


        treeGridModel.setIdField("columnsId");
        treeGridModel.setChildList("aColumnsEntities");

        treeGridModel.setCode("guidePrefer");
        //是否有效
        treeGridModel.setSrc("enable");

        Map<String,Object> fieldMap = new HashMap<String, Object>();
        fieldMap.put("guidePrefer", "guidePrefer");
        fieldMap.put("sort", "sort");
        fieldMap.put("patentIds", "patentIds");
        fieldMap.put("intro", "intro");
        fieldMap.put("isDef", "isDef");
//        fieldMap.put("sortType", "sortType");
        treeGridModel.setFieldMap(fieldMap);
        treeGrids = systemService.treegrid(columnsList, treeGridModel);

        JSONArray jsonArray = new JSONArray();
        for (TreeGrid treeGrid : treeGrids) {

            jsonArray.add(JSON.parse(treeGrid.toJson()));
        }
        return jsonArray;
    }


    /**
     *
     * 商品分类树形下拉框
     * @param request
     * @param comboTree
     * @return
     */
    @RequestMapping(params = "setPFunction")
    @ResponseBody
    public List<ComboTree> setPFunction(HttpServletRequest request, ComboTree comboTree) {
        CriteriaQuery cq = new CriteriaQuery(AColumnsEntity.class);
        if(StringUtil.isNotEmpty(request.getParameter("selfId"))){
            cq.notEq("columnsId", Integer.parseInt(request.getParameter("selfId")));
        }
        if (comboTree.getId() != null) {
            cq.eq("aColumnsEntity.columnsId", Integer.parseInt(comboTree.getId()));
        }
        if (comboTree.getId() == null) {
            cq.isNull("aColumnsEntity");
        }

        cq.eq("deleted",0);

        cq.add();
        List<AColumnsEntity> goodsCategoryList = systemService.getListByCriteriaQuery(cq, false);
        List<ComboTree> comboTrees = new ArrayList<ComboTree>();
        ComboTreeModel comboTreeModel = new ComboTreeModel("columnsId", "title", "aColumnsEntities","patentIds");
        comboTrees = systemService.ComboTree(goodsCategoryList, comboTreeModel, null, true);

        return comboTrees;

    }

    /**
     * 多语言列表页面跳转
     *
     * @return
     */
    @RequestMapping(params = "addorupdate")
    public ModelAndView addorupdate(AColumnsEntity columns,
                                    HttpServletRequest req) {

        if (StringUtil.isNotEmpty(columns.getColumnsId())) {
            columns = systemService.getEntity(AColumnsEntity.class, columns.getColumnsId());
            req.setAttribute("columns", columns);
        }else{
            req.setAttribute("pid",req.getParameter("pid"));
        }
        return new ModelAndView("clound/articleManager/columns/columns");
    }

    /**
     * 添加商品分类
     *
     * @param columns
     * @return
     */
    @RequestMapping(params = "save")
    @ResponseBody
    public AjaxJson save(AColumnsEntity columns, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        if (StringUtil.isNotEmpty(columns.getColumnsId())) {

            AColumnsEntity t = systemService.get(AColumnsEntity.class, columns.getColumnsId());
            try {
                MyBeanUtils.copyBeanNotNull2Bean(columns, t);
//                t.setDeleted(0);//默认没有被删除

                if(t.getaColumnsEntity() != null && null == t.getaColumnsEntity().getColumnsId()){

                    t.setaColumnsEntity(null);

                }

                systemService.saveOrUpdate(t);

                message = "分类标签: " + columns.getTitle() + "修改成功";
                systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
            } catch (Exception e) {
                e.printStackTrace();
                message = "分类标签: " + columns.getTitle() + "修改失败";
            }
        } else {

            //父节点ID为0表示首层节点，加入初始化层级关系
            if(columns.getaColumnsEntity() != null && null == columns.getaColumnsEntity().getColumnsId()){

                columns.setPatentIds(null);
                columns.setaColumnsEntity(null);

            }else{
                //加入层级关系
                if(StringUtil.isEmpty(columns.getPatentIds())){
                    columns.setPatentIds(","
                            + columns.getaColumnsEntity().getColumnsId() + ",");
                }else{

                    columns.setPatentIds(columns.getPatentIds()
                            + columns.getaColumnsEntity().getColumnsId() + ",");
                }
            }

            columns.setDeleted(0);//默认没有被删除
            columns.setCreateTime(new Date());
            systemService.save(columns);

            message = "分类标签: " + columns.getTitle() + "添加成功";
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 删除分类（逻辑删除）
     *
     * @return
     */
    @RequestMapping(params = "delGoodsCategory")
    @ResponseBody
    public AjaxJson delGoodsCategory(AColumnsEntity columns, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        columns = systemService.getEntity(AColumnsEntity.class, columns.getColumnsId());

        //设置为删除
        columns.setDeleted(1);

        systemService.saveOrUpdate(columns);
        message = "分类标签: " + columns.getTitle() + "删除成功";

        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        j.setMsg(message);
        return j;
    }


    /**
     * 获得分类树下拉框
     * @param request
     * @return
     */
    @RequestMapping(params = "getCategoryTree")
    @ResponseBody
    public List<ComboTree> getCategoryTree(HttpServletRequest request) {
//        findHql不能处理is null条件
//        List<TSDepart> departsList = systemService.findHql("from TSPDepart where TSPDepart.id is null");
        List<AColumnsEntity> goodsCategoryList = systemService.findByQueryString("from AColumnsEntity where aColumnsEntity.columnsId = null");
        List<ComboTree> comboTrees = new ArrayList<ComboTree>();
        ComboTreeModel comboTreeModel = new ComboTreeModel("columnsId", "title", "aColumnsEntities");
        comboTrees = systemService.ComboTree(goodsCategoryList, comboTreeModel, null, true);
        return comboTrees;
    }



    /**
     * 启用、禁用
     *
     * @return
     */
    @RequestMapping(params = "enableGoodsCategory")
    @ResponseBody
    public AjaxJson enableGoodsCategory(AColumnsEntity columns, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        columns = systemService.getEntity(AColumnsEntity.class, columns.getColumnsId());

        //启用、禁用
        if(columns.getEnable() == 0){
            columns.setEnable(1);
            message = "分类标签: " + columns.getTitle() + "被启用成功";
        }else{
            columns.setEnable(0);
            message = "分类标签: " + columns.getTitle() + "被禁用成功";

        }

        systemService.saveOrUpdate(columns);

        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        j.setMsg(message);
        return j;
    }
}
